import os
import subprocess
from multiprocessing import Process

# install node-gyp first
# npm install -g node-gyp

outerdir = ['addons', 'js-native-api', 'node-api']
casedir = []

threads = 16

for i in outerdir:
    os.chdir(i)
    innerdir = [x for x in os.listdir() if os.path.isdir(x)]
    innerdir.remove('__pycache__')
    for dir in innerdir:
        casedir.append(f'{i}/{dir}')
    os.chdir('..')


def run(casedirList, threadNum):
    dirs = [x for x in casedirList if (casedirList.index(x) + 1) % threads == threadNum]
    print(f'Thread{threadNum}: {dirs}')

    for dir in dirs:
        os.chdir(dir)
        cases = [x for x in os.listdir() if x[-3:] == '.js']
        print(f'{dirs.index(dir)}/{len(dirs)} {dir}')
        subprocess.run(['node-gyp', 'configure', 'build'])

        for case in cases:
            if (os.path.exists(f'{case}.exitcode')):
                continue

            print(
                f'Thread {i}: {cases.index(case)+1}/{len(cases)} {dir}/{case}\n')
            proc = subprocess.run(['node', case], capture_output=True)
            with open(f'{case}.exitcode', 'w', encoding='utf-8') as f:
                f.write(str(proc.returncode))
            with open(f'{case}.out', 'w', encoding='utf-8') as f:
                f.writelines(proc.stdout.decode('utf-8'))
            with open(f'{case}.err', 'w', encoding='utf-8') as f:
                f.writelines(proc.stderr.decode('utf-8'))
        os.chdir('../..')


plist = []
for i in range(threads):
    plist.append(Process(target=run, args=(casedir, i)))
    plist[i].start()
